<template>
  <div class="page-wrapper">
    <!-- 步骤条区域 -->
    <div class="step-container">
      <el-steps
        style="width: 100%;" 
        align-center 
        :active="activeStep" 
        finish-status="success"
        @step-click="handleStepClick" 
      >
        <el-step title="申请退住" :status="getStepStatus(1)" />
        <el-step title="申请审批" :status="getStepStatus(2)" />
        <el-step title="解除合同" :status="getStepStatus(3)" />
        <el-step title="调整账单" :status="getStepStatus(4)" />
        <el-step title="账单审批" :status="getStepStatus(5)" />
        <el-step title="退住审批" :status="getStepStatus(6)" />
        <el-step title="费用清算" :status="getStepStatus(7)" />
      </el-steps>
    </div>

    <!-- 内容区域：传递stepNum和dropContentId给子组件 -->
    <div class="content-area">
      <component 
        :is="currentComponent" 
        :key="activeStep" 
        ref="stepComponentRef" 
        @submit-step="handleChildSubmitSuccess"  
        @back-to-list="handleChildGoBack"       
        :step-num="activeStep"  
        :drop-content-id="dropContentId"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';  // 新增：用于获取路由参数
import { ElMessage } from 'element-plus';

// 导入子组件
import Drop1 from './dropcomponents/drop1.vue';
import Drop2 from './dropcomponents/drop2.vue';
import Drop3 from './dropcomponents/drop3.vue';
import Drop4 from './dropcomponents/drop4.vue';
import Drop5 from './dropcomponents/drop5.vue';
import Drop6 from './dropcomponents/drop6.vue';
import Drop7 from './dropcomponents/drop7.vue';

// 路由相关：获取外部传递的参数（从列表页点击进入时）
const router = useRouter();
const route = useRoute();  // 用于获取URL中的参数

// 核心状态管理
const activeStep = ref(1);                  // 当前激活的步骤
const finishedSteps = ref([]);              // 已完成的步骤
const totalSteps = 7;                       // 总步骤数
const stepComponentRef = ref(null);         // 子组件引用
const dropContentId = ref('');              // 数据ID（跨步骤传递）

// 初始化：从路由参数获取stepNum和dropContentId（列表页点击进入时）
onMounted(() => {
  // 从URL参数中获取步骤数（如：/detail?stepNum=3&dropContentId=123）
  const { stepNum, id } = route.query;
  

  if (stepNum && !isNaN(stepNum) && stepNum >= 1 && stepNum <= totalSteps) {
    activeStep.value = Number(stepNum);  // 初始化到指定步骤
    // 标记所有小于当前步骤的为已完成（例如：跳转到步骤3，则1、2为已完成）
    finishedSteps.value = Array.from({ length: activeStep.value - 1 }, (_, i) => i + 1);
  }else if (stepNum == -1) {
    activeStep.value = 7;
    finishedSteps.value = [1, 2, 3, 4, 5, 6, 7];
  }

  if (id) {
    dropContentId.value = id;  // 初始化数据ID
  }
});

// 步骤-组件映射
const stepComponents = [
  { step: 1, component: Drop1 },
  { step: 2, component: Drop2 },
  { step: 3, component: Drop3 },
  { step: 4, component: Drop4 },
  { step: 5, component: Drop5 },
  { step: 6, component: Drop6 },
  { step: 7, component: Drop7 },
];

// 计算当前显示的组件
const currentComponent = computed(() => {
  const target = stepComponents.find(item => item.step === activeStep.value);
  return target ? target.component : Drop1;
});

// 步骤状态判断
const getStepStatus = (step) => {
  if (finishedSteps.value.includes(step)) return "success";
  if (step === activeStep.value) return "process";
  return "wait";
};

// 处理子组件提交：更新步骤和数据ID
const handleChildSubmitSuccess = async (childData = {}) => {
  try {
    // 1. 子组件表单验证
    if (stepComponentRef.value?.validateForm) {
      const isValid = await stepComponentRef.value.validateForm();
      if (!isValid) {
        ElMessage.warning('请完善当前步骤的必填信息');
        return;
      }
    }

     // 2. 更新dropContentId（核心：保存子组件传递的ID）
    if (childData.dropContentId || childData.newDropContentId) {
      dropContentId.value = childData.newDropContentId || childData.dropContentId;
      console.log('父组件更新ID：', dropContentId.value); // 这里需打印确认
    }

    // 3. 标记当前步骤为已完成
    if (!finishedSteps.value.includes(activeStep.value)) {
      finishedSteps.value.push(activeStep.value);
    }

    // 4. 推进到下一步
    if (activeStep.value < totalSteps) {
      activeStep.value += 1;
      ElMessage.success('提交成功，进入下一步');
    } else {
      ElMessage.success('所有退住流程已完成！');
      setTimeout(() => {
        router.push('/togetherwork/togetherwork1/myapply');
      }, 2000);
    }
  } catch (error) {
    console.error('提交失败：', error);
    ElMessage.error('提交失败，请重试');
  }
};

// 处理步骤条点击切换
const handleStepClick = (step) => {
  const clickedStep = step.index + 1;
  // 仅允许跳转到已完成步骤或当前步骤
  if (finishedSteps.value.includes(clickedStep) || clickedStep === activeStep.value) {
    activeStep.value = clickedStep;
  } else {
    ElMessage.info('请先完成当前步骤，再进行后续操作');
  }
};

// 处理返回列表
const handleChildGoBack = () => {
  router.back();
};
</script>

<!-- 完全保留你原有的样式代码，不做任何修改 -->
<style scoped>
.page-wrapper {
  display: flex;
  flex-direction: column;
  padding: 20px;
  box-sizing: border-box;
}
.step-container {
  margin-bottom: 24px;
}
.content-area {
  flex: 1;
  min-height: 300px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  padding: 20px;
  margin-bottom: 24px;
  background: #fff;
}
</style>